﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeIT.Deo.Negocios;
using System.Data.Entity;
using System.IO;
using System.Web.UI.HtmlControls;

namespace MakeIT.Deo.Apresentacao
{
    public partial class CadastroContato : System.Web.UI.Page
    {
        usuario usuarioVO = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            usuarioVO = (usuario)this.Session["userActive"];
        }

        protected void cbxTodosContatos_CheckedChanged(object sender, EventArgs e)
        {
            foreach (GridViewRow gvr in this.GridViewContato.Rows)
            {
                ((CheckBox)gvr.Cells[0].Controls[0]).Checked = this.cbxTodosContatos.Checked;
            }
        }


        /// <summary>
        /// Manipula o evento do bot&atilde;o btnPesquisa
        /// </summary>
        /// <param name="sender">Objeto disparador do evento</param>
        /// <param name="e">Argumento do evento</param>
        protected void btnPesquisa_Click(object sender, EventArgs e)
        {

            //Declara objetos
            int? idContato = null;
            string nome = null;
            string email = null;
            string assunto = null;
            DateTime? dtIni = null;
            DateTime? dtFin = null;

            try
            {
                if (!string.IsNullOrEmpty(this.txtId.Text))
                {
                    idContato = Int32.Parse(this.txtId.Text);
                }

                if (!string.IsNullOrEmpty(this.txtNome.Text))
                {
                    nome = this.txtNome.Text;
                }

                if (!string.IsNullOrEmpty(this.txtEmail.Text))
                {
                    email = this.txtEmail.Text;
                }

                if (!string.IsNullOrEmpty(this.txtAssunto.Text))
                {
                    assunto = this.txtAssunto.Text;
                }

                if (!string.IsNullOrEmpty(this.txtInicio.Text))
                {
                    try
                    {
                        dtIni = new DateTime(int.Parse(this.txtInicio.Text.Substring(6, 4)),
                                            int.Parse(this.txtInicio.Text.Substring(3, 2)),
                                            int.Parse(this.txtInicio.Text.Substring(0, 2)));
                    }
                    catch (Exception ex)
                    {
                        Util.ExibeAlert(this, "Data inicial incorreta!");
                        return;
                    }
                }
                if (!string.IsNullOrEmpty(this.txtFinal.Text))
                {
                    try
                    {
                        dtFin = new DateTime(int.Parse(this.txtFinal.Text.Substring(6, 4)),
                                             int.Parse(this.txtFinal.Text.Substring(3, 2)),
                                             int.Parse(this.txtFinal.Text.Substring(0, 2)));
                    }
                    catch (Exception ex)
                    {
                        Util.ExibeAlert(this, "Data final incorreta!");
                        return;
                    }
                }
                //
                List<contato> listContato = new ContatoBO().RecuperaContato(idContato, nome, email, assunto, dtIni, dtFin);
                this.Session["dataSource"] = listContato;

                this.GridViewContato.DataSource = listContato;

                //Vincula os dados
                this.GridViewContato.DataBind();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            if (Session["dataSource"] != null)
            {

                List<contato> listContato = (List<contato>)Session["dataSource"];

                Response.Clear();
                Response.AddHeader("content-disposition", "attachment;filename=Contato.csv");
                Response.Charset = "";

                // If you want the option to open the Excel file without saving than
                // comment out the line below
                // Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "application/ms-excel";
                System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                //System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

                //GridView gv1 = new GridView();
                //gv1.DataSource = listContato;
                //gv1.DataBind();

                //gv1.AllowPaging = false;
                //gv1.AllowSorting = false;

                stringWrite.Write("\"ID\";" +
                  "\"Envio\";" +
                  "\"Nome\";" +
                  "\"Email\";" +
                  "\"Regiao\";" +
                  "\"Telefone\";" +
                  "\"Assunto\";" +
                  "\"Mensagem\"\n");
                
                foreach (contato cVO in listContato)
                {
                    stringWrite.Write(cVO.idcontato.ToString() + ";" +
                                      cVO.envio.Value.ToString("dd/MM/yyyy") + ";" +
                                      "\"" + cVO.nome + "\"" + ";" +
                                      "\"" + cVO.email + "\"" + ";" +
                                      "\"" + cVO.regiao + "\"" + ";" +
                                      "\"" + cVO.telefone + "\"" + ";" +
                                      "\"" + cVO.assunto + "\"" + ";" +
                                      "\"" + cVO.mensagem + "\"" + "\n");
                }

                //gv1.RenderControl(htmlWrite);
                Response.Write(stringWrite.ToString());
                Response.End();
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
        }

        protected void btnExcluir_Click(object sender, EventArgs e)
        {
            try
            {
                ContatoBO contatoBO = new ContatoBO();
                foreach (GridViewRow gvr in this.GridViewContato.Rows)
                {
                    if (((CheckBox)gvr.Cells[0].Controls[0]).Checked)
                    {
                        contato contatoVO = new contato();
                        contatoVO.idcontato = int.Parse(gvr.Cells[1].Text);
                        contatoBO.DeletaContato(contatoVO);
                    }
                }
                // Exibe msg de sucesso ao salvar registro
                Util.ExibeAlert(this, "Registros excluidos com sucesso!");

                btnPesquisa_Click(sender, e);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}
